package com.example.lwt.stopwatch;

import android.os.Handler;
import android.widget.TextView;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;

class Watch implements Runnable, Externalizable {
    int seconds;
    IWatchState state;
    Handler mHandler;
    TextView textView;

    public Watch() {
    }

    Watch(TextView textView) {
        this.mHandler = new Handler();
        this.textView = textView;
    }

    @Override
    public void writeExternal(ObjectOutput objectOutput) throws IOException {
        objectOutput.writeInt(seconds);
        objectOutput.writeObject(state);
        System.out.println("序列化");
    }

    @Override
    public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException {
        this.seconds = objectInput.readInt();
        this.state = (IWatchState) objectInput.readObject();
        System.out.println("反序列化");
    }


    @Override
    public void run() {
        mStarted = true;
        if (this.state != null) {
            state.runTimer(this);
        }
        mHandler.postDelayed(this, 1000);
    }

    void update() {
        int hours = this.seconds / 3600;
        int minutes = (this.seconds % 60) / 60;
        int secs = this.seconds % 60;
        String time = String.format("%d:%02d:%02d", hours, minutes, secs);
//        System.out.println(mHandler + " seconds = " + seconds + "  Watch " + this);
        textView.setText(time);
    }

    boolean mStarted;

    void start() {
        if (this.state instanceof WatchStateRun) {
            return;
        }

        this.state = new WatchStateRun();
        if (!mStarted) {
            mHandler.postDelayed(this, 1000);
        }
//        System.out.println("START!!!!!!!!!!!!!!!!");
    }

    void stop() {
        if (this.state instanceof WatchStateStop) {
            return;
        }
        this.state = new WatchStateStop();
    }

    void reset() {
        this.seconds = 0;
        this.update();
    }
}

interface IWatchState extends Serializable {
    void runTimer(Watch watch);
}

class WatchStateRun implements IWatchState {

    @Override
    public void runTimer(Watch watch) {
        watch.seconds++;
        watch.update();

    }
}

class WatchStateStop implements IWatchState {
    @Override
    public void runTimer(Watch watch) {
    }
}